# 三方包
from datetime import datetime, timedelta
from typing import Union, Any
from jose import jwt
import hashlib
from fastapi.responses import JSONResponse
from fastapi import status

# 自建包
from setting import settings

# 常量
ALGORITHM = 'HS256'


# generate access token
def create_access_token(
        subject: Union[str, Any], expires_delta: timedelta = None
) -> str:
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(
            minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES
        )
    to_encode = {
        'exp': expire,
        'sub': str(subject)
    }
    encoded_jwt = jwt.encode(
        to_encode, settings.SECRET_KEY, algorithm=ALGORITHM
    )
    return encoded_jwt


# 加密MD5
def computeMD5(message):
    m = hashlib.md5()
    m.update(message.encode(encoding='utf-8'))
    return m.hexdigest()


# SelfJSONResponse
def SelfJSONResponse(code, data=None, msg=None):
    if code >= 500:
        return JSONResponse(status_code=status.HTTP_200_OK, content={'code': code, 'msg': msg})
    else:
        return JSONResponse(status_code=status.HTTP_200_OK, content={'code': code, 'data': data, 'msg': msg})


# SelectJSONResponse
def SelectJSONResponse(code, rows=None, total=0, msg=None):
    if code >= 500:
        return JSONResponse(status_code=status.HTTP_200_OK, content={'code': code, 'msg': msg})
    else:
        return JSONResponse(status_code=status.HTTP_200_OK,
                            content={'code': code, 'rows': rows, 'total': total, 'msg': msg})
